/** 文档目录 */
import {createElement} from "./utils/element";
import {setTitleNumber, getTitleTypes, getTitleAttributeKey} from "./utils/title";

class Cat2DocList {
  #parentElement = null;
  #listDiv = null;
  constructor(parentElement) {
    this.#parentElement = parentElement;
    this.#init(parentElement);
  }
  /** 初始化 */
  #init(parentElement) {
    this.#listDiv = Cat2DocList.#createListDiv(parentElement);
  }
  /** 释放 */
  destory() {
    this.#listDiv = null;
  }
  /** 加载列表 */
  loadList(docDiv) {
    this.#listDiv.innerHTML = '';
    docDiv.childNodes.forEach(dom=>{
      if(dom.childNodes && dom.childNodes.length>0) {
        const titleEle = dom.childNodes[0];
        if (getTitleTypes().indexOf(titleEle.tagName) >= 0) {
          this.#createListItem(dom, titleEle);
        }
      }
    });
    setTitleNumber(this.#listDiv, 0,0,this.#listDiv.childNodes.length-1,null);
  }
  /** 重置 */
  reset() {
    this.#listDiv.innerHTML = null;
  }
  /** 创建目录 */
  #createListItem(parentNode, dom) {
    let id = parentNode.getAttribute('id');
    const opts = { attr: {}}
    opts.attr[getTitleAttributeKey()]=id;
    let p = createElement('p', this.#listDiv, opts);
    let ele = createElement(dom.tagName, p, {});
    ele.innerHTML = dom.textContent;
    ele.addEventListener('click', Cat2DocList.#handleListItemClick.bind(this))
    return p;
  }
  /** 创建目录列表 */
  static #createListDiv(parent) {
    return createElement('div', parent, {
      className: 'c2d-list',
      style: {
        zIndex: '1'
      }
    });
  }
  /** 处理点击目录事件 */
  static #handleListItemClick(event) {
    const id = event.target.parentNode.getAttribute(getTitleAttributeKey());
    let anchor = document.getElementById(id);
    if(anchor) {
      anchor.scrollIntoView();
      // 触发自定义事件
      let anchorEvent = new CustomEvent("anchor", {
        detail: { id: id }
      });
      window.dispatchEvent(anchorEvent);
    }
  }
}

export default Cat2DocList;
